Skip to content

perf: specialize scalar aggregate FILTER evaluation - #27321

Open
xudong963 wants to merge 4 commits into
apache:mainfrom
xudong963:xudong963/scalar-aggregate-filter
Open

xudong963 wants to merge 4 commits into
apache:mainfrom
xudong963:xudong963/scalar-aggregate-filter

Conversation

@xudong963

@xudong963 xudong963 commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Which issue does this PR close?

Follow-up to #27119, specifically the scalar FILTER review discussion.

Rationale for this change

An aggregate FILTER that evaluates to a scalar boolean currently expands that value into a batch-sized BooleanArray before deciding which rows to evaluate. Scalar predicates are common: literal and constant-folded predicates (such as FILTER (WHERE 1 = 2)) and prepared statement parameters (FILTER (WHERE $1)) remain in the physical plan as literals, and scalar-returning UDFs return scalars at runtime. They can avoid this allocation and bitmap scanning.

What changes are included in this PR?

  • Evaluate each aggregate FILTER to one of three selections: every row, no row, or the rows where a boolean array is true. Scalar true selects every row; scalar false and NULL select none. Arrays that select every row or none are folded into the same two cases. The predicate is still evaluated for every batch, since a runtime scalar can change between batches.
  • Ungrouped and compacting grouped aggregation borrow the input when every row is selected, and use empty typed arguments without evaluating them when no row is selected. Groups whose rows are all rejected are kept.
  • Skip-partial conversion uses the unfiltered argument path when every row is selected. When no row is selected, it skips argument evaluation but still passes an all-false filter: GroupsAccumulator::convert_to_state needs it to produce empty states, because aggregates such as array_agg keep NULL arguments.
  • Add SQL/UDF and SQLLogicTest regressions. Benchmark code and reproduction commands are included below.

What is the testing strategy for this PR?

  • cargo fmt --all and every ./dev/rust_lint.sh step passed on the latest commit, including Clippy with all targets/features and -D warnings, dependency checks, Rust documentation, and the documentation website build. The exception is cargo audit, which could not load the advisory database locally because the installed cargo-audit does not support CVSS 4.0 entries; it passed for the first commit.
  • The inline benchmark snippet below builds successfully with release-nonlto.
  • The extended workspace test command from AGENTS.md passed for the first commit: 13,630 Rust tests, zero failures, eight ignored; all 548 SQLLogicTest files passed. With the latest commit merged into current main, all datafusion-physical-plan unit tests, the core aggregate integration tests, and all SQLLogicTest files pass.
  • The new SQL/UDF test covers changing scalar true/false/NULL results across differently sized batches, nullable arguments, literal arguments, rejected division-by-zero expressions, retained empty groups, array_agg, multiple partitions, and skip-partial conversion. It checks skipped_aggregation_rows to verify that conversion was exercised.
  • The new SQLLogicTest cases cover literal, constant-folded, and prepared statement predicates in ungrouped, grouped, and skip-partial aggregation.
  • Both the SQL/UDF test and the SQLLogicTest cases fail if skip-partial conversion drops the all-false filter when no row is selected.
  • A unit test covers folding scalar and array predicates into the three selections.

Compared with main 34eb6dc5b, using the same benchmark source and release-nonlto builds (65,536 rows, batches of 8,192):

Ungrouped FILTER main median PR median Change
Scalar true 14.74 us 13.61 us -7.7%
Scalar false 8.03 us 5.70 us -29.0%
Scalar NULL 10.13 us 5.71 us -43.6%
Scalar varying between batches 10.49 us 7.99 us -23.8%

These are medians of three runs per build in alternating order, with 30 Criterion samples, 0.5 s warm-up, and 1 s measurement per case. The suite also covers grouped and skip-partial execution, shuffled 50%-selective array filters, and unfiltered controls.

Grouped and skip-partial timings did not change beyond run-to-run variation, about ±4% on this shared macOS machine: those paths already skipped batches with no selected rows. In three longer runs per build (60 samples, 1 s warm-up, 3 s measurement, alternating order), the array-filter, unfiltered, and scalar-true controls changed by -2.4% to +2.6% (table below). These local microbenchmarks are not end-to-end query speedup claims.

Benchmark code and reproduction commands

The following optional benchmark exercises scalar true, false, NULL, and
batch-varying predicates in ungrouped, grouped, and skip-partial aggregation.
A shuffled 50%-selective array predicate and an unfiltered aggregate serve as
controls. It uses the existing in-memory AggregateExec benchmark helpers to
exclude SQL planning and file I/O.

To run it locally, paste the function below into
datafusion/physical-plan/benches/aggregate_filter.rs, immediately before
aggregate_filter_benchmark. In aggregate_filter_benchmark, add this call
immediately after let runtime = Runtime::new().unwrap();:

benchmark_scalar_filters(c, &runtime);
fn benchmark_scalar_filters(c: &mut Criterion, runtime: &Runtime) {
    use datafusion_common::ScalarValue;
    use datafusion_execution::config::SessionConfig;
    use datafusion_expr::{ColumnarValue, Volatility, create_udf};
    use datafusion_physical_expr::ScalarFunctionExpr;

    let schema = schema();
    let batch_filter = Arc::new(create_udf(
        "batch_filter",
        vec![DataType::Boolean],
        DataType::Boolean,
        Volatility::Volatile,
        Arc::new(|args| match &args[0] {
            ColumnarValue::Array(array) => Ok(ColumnarValue::Scalar(
                ScalarValue::try_from_array(array, 0)?,
            )),
            scalar => Ok(scalar.clone()),
        }),
    ));
    let varying: Arc<dyn PhysicalExpr> = Arc::new(
        ScalarFunctionExpr::try_new(
            batch_filter,
            vec![col("include_a", &schema).unwrap()],
            &schema,
            Arc::default(),
        )
        .unwrap(),
    );
    let filters = [
        ("true", Some(lit(true))),
        ("false", Some(lit(false))),
        ("null", Some(lit(ScalarValue::Boolean(None)))),
        ("varying", Some(varying)),
        ("array_50_percent", Some(col("include_a", &schema).unwrap())),
        ("unfiltered", None),
    ];
    let config = SessionConfig::new()
        .set_usize(
            "datafusion.execution.skip_partial_aggregation_probe_rows_threshold",
            0,
        )
        .set(
            "datafusion.execution.skip_partial_aggregation_probe_ratio_threshold",
            &ScalarValue::Float64(Some(0.0)),
        );
    let task_ctx = Arc::new(TaskContext::default().with_session_config(config));
    for (name, mode, grouped) in [
        ("ungrouped", AggregateMode::Single, false),
        ("grouped", AggregateMode::Single, true),
        ("skip_partial", AggregateMode::Partial, true),
    ] {
        let batches = make_batches(
            Some(50),
            if mode == AggregateMode::Partial {
                NUM_ROWS
            } else {
                16
            },
        );
        let input: Arc<dyn ExecutionPlan> =
            TestMemoryExec::try_new_exec(&[batches], Arc::clone(&schema), None).unwrap();
        let mut group = c.benchmark_group(format!("scalar_aggregate_filter/{name}"));
        for (filter_name, filter) in &filters {
            let group_by = if grouped {
                PhysicalGroupBy::new_single(vec![(
                    col("group_key", &schema).unwrap(),
                    "group_key".to_string(),
                )])
            } else {
                PhysicalGroupBy::default()
            };
            let plan: Arc<dyn ExecutionPlan> = Arc::new(
                AggregateExec::try_new(
                    mode,
                    group_by,
                    vec![aggregate_expr(&schema, 0, ArgumentKind::Column)],
                    vec![filter.clone()],
                    Arc::clone(&input),
                    Arc::clone(&schema),
                )
                .unwrap(),
            );
            group.bench_function(*filter_name, |b| {
                b.iter(|| {
                    black_box(
                        runtime
                            .block_on(collect(Arc::clone(&plan), Arc::clone(&task_ctx)))
                            .unwrap(),
                    );
                });
            });
        }
        group.finish();
    }
}

Run from the repository root:

cargo bench --profile release-nonlto -p datafusion-physical-plan \
    --features test_utils --bench aggregate_filter -- \
    scalar_aggregate_filter --warm-up-time 0.5 --measurement-time 1 \
    --sample-size 30 --noplot

For comparisons, apply the same snippet and registration call to both revisions,
use separate CARGO_TARGET_DIR directories, and alternate the run order. The
benchmark uses 65,536 rows in batches of 8,192, with 16 groups for grouped
aggregation and one group per row for skip-partial aggregation. The latter sets
both skip-partial probe thresholds to zero. The varying predicate returns the
first shuffled filter value in each batch as a scalar.

To repeat the longer control measurements:

cargo bench --profile release-nonlto -p datafusion-physical-plan \
    --features test_utils --bench aggregate_filter -- \
    'scalar_aggregate_filter/(grouped|skip_partial)/(array_50_percent|unfiltered|true)$' \
    --warm-up-time 1 --measurement-time 3 --sample-size 60 --noplot
Control main median PR median Change
Grouped array filter 218.56 us 217.05 us -0.7%
Grouped unfiltered 166.58 us 167.64 us +0.6%
Grouped scalar true 168.50 us 165.86 us -1.6%
Skip-partial array filter 205.96 us 205.88 us -0.0%
Skip-partial unfiltered 138.98 us 142.62 us +2.6%
Skip-partial scalar true 139.15 us 135.87 us -2.4%

Are there any user-facing changes?

Lower overhead for aggregate FILTER predicates that evaluate to a scalar. SQL results and public APIs are unchanged.

🤖 Generated with Claude Code

@github-actions github-actions Bot added core Core DataFusion crate physical-plan Changes to the physical-plan crate labels Nov 11, 2026
@xudong963
xudong963 marked this pull request as ready for review November 12, 2026 02:26
@xudong963
xudong963 requested a review from alamb November 26, 2026 02:33
Evaluate an aggregate FILTER to All, Empty, or Rows, folding arrays that
select every row or none into the same cases as scalar predicates. The
ungrouped, compacting, and skip-partial paths share this representation,
and the ungrouped path now also skips argument evaluation for arrays that
reject every row.

Cover literal, constant-folded, and prepared statement predicates in
SQLLogicTest. Check array_agg, which keeps NULL arguments, so skip-partial
conversion must still pass a rejecting filter when no row is selected.
@github-actions github-actions Bot added the sqllogictest SQL Logic Tests (.slt) label Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Core DataFusion crate physical-plan Changes to the physical-plan crate sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant